package io.gitee.caoxiaoyu97.log4j.defender.message.log;

import io.gitee.caoxiaoyu97.log4j.defender.constants.DefenderConstants;
import io.gitee.caoxiaoyu97.log4j.defender.message.log.bean.BeanDefender;
import io.gitee.caoxiaoyu97.log4j.defender.properties.DefenderKeyProperties;

import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

public class SpringBeanDefender extends AbstractLogDefender<BeanDefender> {
    protected List<BeanDefender> orderedBeanDefenders;

    public SpringBeanDefender(DefenderKeyProperties properties) {
        super(properties);
    }


    protected <T> List<T> createBeanDefenderInstances(List<String> names, Class<T> type, ClassLoader classLoader, Class<?>[] parameterTypes, DefenderKeyProperties args) {
        List<T> instances = new LinkedList<>();
        if (CollectionUtils.isEmpty(names)) {
            return instances;
        }
        for (String name : names) {
            try {
                Class<?> instanceClass = ClassUtils.forName(name, classLoader);
                Assert.isAssignable(type, instanceClass);
                Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
                instances.add((T) BeanUtils.instantiateClass(constructor, new Object[]{args}));
            } catch (Throwable ex) {
                throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
            }
        }
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }

    protected Set<BeanDefender> transformToMatcher(DefenderKeyProperties properties) {
        HashSet<BeanDefender> defenders = new HashSet<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        List<String> names = SpringFactoriesLoader.loadFactoryNames(BeanDefender.class, classLoader);
        names = keepSpiNames(properties, names);
        List<BeanDefender> beanDefenders = createBeanDefenderInstances(names, BeanDefender.class, classLoader, new Class[]{DefenderKeyProperties.class}, properties);

        this.orderedBeanDefenders = beanDefenders;
        defenders.addAll(beanDefenders);
        return defenders;
    }

    private List<String> keepSpiNames(DefenderKeyProperties properties, List<String> names) {
        if (!StringUtils.isEmpty(properties.getKeys()) && !properties.getKeys().equals("*")) {
            List<String> toKeepNames = new LinkedList<>();
            for (String key : DefenderConstants.DEFAULT_SPLIT_PATTERN.split(properties.getKeys())) {
                if (names.contains(key)) {
                    toKeepNames.add(key);
                }
            }
            return toKeepNames;
        }
        return names;
    }


    public StringBuilder doDesensitize(StringBuilder inputOrigin) {
        StringBuilder input = inputOrigin;
        for (BeanDefender defender : this.orderedBeanDefenders) {
            input = defender.doDefender(input);
        }
        return input;
    }


    protected boolean isQuickMatch(StringBuilder input) {
        return this.toMatchKeys.stream().anyMatch(it -> it.isQuickMatch(input));
    }
}
